#pragma once

#include <iostream>
// 随机任务所需要的头文件
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <stdlib.h>


#define TaskNum 3

typedef void (*task_t)();

void Print()
{
    std::cout << "i'm a print task!" << std::endl;
}

void Download()
{
    std::cout << "i'm a download task!" << std::endl;
}

void FlushStdout()
{
    std::cout << "i'm a flushstdout task!" << std::endl;
}

task_t tasks[TaskNum];

void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 12457); // 用于增加随机数
    tasks[0] = Print;
    tasks[1] = Download;
    tasks[2] = FlushStdout;
}

// 执行任务
void ExcuteTask(int number)
{
    if (number < 0 || number > 2)
        return;
    tasks[number]();
}

int SelectTask()
{
    return rand() % TaskNum; // 这里就只会有0,1,2几个值
}

void work()
{
    while (true)
    {
        int command = 0;
        // 读上父进程0给我写的整数赋给command
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid is : " << getpid() << ", header task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "sub process : " << getpid() << " quit" << std::endl;
            break;
        }
    }
}

void work1()
{
    while (true)
    {
        int command = 0;
        // 读上父进程0给我写的整数赋给command
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid is : " << getpid() << ", header task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "sub process : " << getpid() << " quit" << std::endl;
            break;
        }
    }
}

void work2()
{
    while (true)
    {
        int command = 0;
        // 读上父进程0给我写的整数赋给command
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid is : " << getpid() << ", header task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "sub process : " << getpid() << " quit" << std::endl;
            break;
        }
    }
}